//
// Created by shenbin on 2022/4/17.
// https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
//

#ifndef ALGORITHM_TRAINNING_C02_LC150_H
#define ALGORITHM_TRAINNING_C02_LC150_H

#include<vector>
#include<stack>
#include<string>

using namespace std;

class LeetCode150 {
public:
    int evalRPN(vector<string> &tokens) {
        for (string token: tokens) {
            if (token == "+" || token == "-" || token == "*" || token == "/") {
                int y = s.top();
                s.pop();
                int x = s.top();
                s.pop();
                int z = calc(x, y, token);
                s.push(z);
            } else {
                s.push(atoi(token.c_str()));
            }
        }
        return s.top();

    }

private:
    stack<int> s;

    /**
     * 根据操作符计算两个数的运算结果，并返回。
     * @param x
     * @param y
     * @param op
     * @return
     */
    int calc(int x, int y, string &op) {
        if (op == "+") return x + y;
        if (op == "-") return x - y;
        if (op == "*") return x * y;
        if (op == "/") return x / y;
        return 0;
    }
};

#endif //ALGORITHM_TRAINNING_C02_LC150_H
